const mongoose = require('./db');

let lxtuserSchema = new mongoose.Schema({
    username: String,
    shenfen: String,
    phone: String,
    email: String,
    password: String,
    // 第三方登录字段
    socialUid: {
        type: String,
        default: null       // 默认为null，普通注册用户不需要
    },
    nickname: {
        type: String,
        default: ''         // 默认为空字符串
    },
    faceimg: {
        type: String,
        default: ''         // 默认为空字符串
    },
    loginType: {
        type: String,
        default: 'normal'   // 默认为普通登录
    },
    address: {
        type: String,
        default: ''
    },
    createTime: {
        type: Date,
        default: Date.now
    },
    updateTime: {
        type: Date,
        default: Date.now
    },
    loginTime: {
        type: Date,
        default: Date.now
    },
    loginip: {
        type: String,
        default: ''
    },
    // 登录历史记录（包含地理位置信息）
    loginHistory: [{
        ip: {
            type: String,
            required: true
        },
        location: {
            country: String,
            region: String,
            city: String,
            latitude: Number,
            longitude: Number,
            isp: String,
            timezone: String
        },
        timestamp: {
            type: Date,
            default: Date.now
        },
        userAgent: String,
        loginMethod: {
            type: String,
            enum: ['password', 'code', 'social'],
            default: 'password'
        },
        isSecureLogin: {
            type: Boolean,
            default: false // 是否为二次验证后的登录
        },
        riskLevel: {
            type: String,
            enum: ['low', 'medium', 'high'],
            default: 'low'
        }
    }],
    // 安全设置
    securitySettings: {
        enableLocationCheck: {
            type: Boolean,
            default: true // 是否启用异地登录检测
        },
        isRiskUser: {
            type: Boolean,
            default: false // 是否为风险用户（强制二次验证）
        },
        riskUserReason: {
            type: String,
            default: '' // 标记为风险用户的原因
        },
        riskUserMarkedAt: {
            type: Date,
            default: null // 标记为风险用户的时间
        },
        trustedLocations: [{
            city: String,
            region: String,
            country: String,
            latitude: Number,
            longitude: Number,
            addedAt: {
                type: Date,
                default: Date.now
            }
        }],
        lastSecurityVerification: {
            type: Date,
            default: null
        }
    }
})

let lxtuserModel = mongoose.model('lxtuser', lxtuserSchema, 'lxtuser');


//登录用户
const userSchema = new mongoose.Schema({
    id: {
        type: String,
        required: true,
        unique: true,
        validate: {
            validator: function(v) {
                return /^(100|200)\d+$/.test(v); // 确保ID以100或200开头
            },
            message: props => `${props.value} 不是有效的用户ID! ID必须以100(管理员)或200(教师)开头`
        }
    },
    username: {
        type: String,
        required: true,
        unique: true,
        trim: true,
    },
    password: {
        type: String,
        required: true,
        minlength: 6,
        select: false
    }
});

// 添加虚拟字段role，根据ID判断用户类型
userSchema.virtual('role').get(function() {
    if (this.id.startsWith('100')) {
        return 'superAdmin';
    } else if (this.id.startsWith('200')) {
        return 'teacher';
    }
    return 'unknown';
});

const User = mongoose.model('User', userSchema);

//学生表
const studentSchema = new mongoose.Schema({
    // 学生ID (学号)
    studentId: {
        type: String,
        required: true,
        unique: true
    },
    // 学生姓名
    name: {
        type: String,
        required: true,
        trim: true,
        maxlength: 20
    },
    // 性别
    gender: {
        type: String,
        required: true,
        enum: ['男', '女', '其他'],
        default: '男'
    },
    // 手机号
    phone: {
        type: String,
        required: true,
        validate: {
            validator: function(v) {
                return /^1[3-9]\d{9}$/.test(v);
            },
            message: props => `${props.value} 不是有效的手机号码!`
        }
    },
    // 所属年级
    class: {
        type: String,
        required: true,
        enum: ['高一', '高二', '高三']
    },
    // 成绩平均分
    averageScore: {
        type: Number,
        required: true,
        min: 0,
        max: 100,
        set: v => parseFloat(v.toFixed(1)) // 保留1位小数
    },
    // 账户状态
    isActive: {
        type: Boolean,
        required: true,
        default: true
    }
});
const Student = mongoose.model('Student', studentSchema);

const teacherSchema = new mongoose.Schema({
    // 讲师名称
    name: {
        type: String,
        required: true,
        trim: true,
        maxlength: 20
    },
    // 讲师头像URL
    avatar: {
        type: String,
        default: 'https://randomuser.me/api/portraits/men/1.jpg'
    },
    // 讲师简介 (简短介绍)
    briefIntro: {
        type: String,
        required: true,
        maxlength: 100,
        default: '专注原型设计教学'
    },
    // 详细介绍 (HTML格式)
    detailedIntro: {
        type: String,
        default: ''
    },
    // 手机号
    phone: {
        type: String,
        default: ''
    },
    // 上传人 (关联管理员ID)
    uploader: {
        type: String,
        required: true,
        ref: 'User' 
    },
    // 添加时间
    createdAt: {
        type: Date,
        default: Date.now
    }
});

const Teacher = mongoose.model('Teacher', teacherSchema);

// 视频资源表
const videoResourceSchema = new mongoose.Schema({
    // 编号（自动生成的唯一标识）
    id: {
        type: String,
        required: true,
        unique: true,
        default: () => `vid_${Math.random().toString(36).substr(2, 9)}` // 生成唯一ID
    },
    
    // 视频名称
    name: {
        type: String,
        required: [true, '视频名称不能为空'],
        trim: true,
        maxlength: [100, '视频名称不能超过100个字符']
    },
    
    // 视频文件URL
    videoUrl: {
        type: String,
        required: [true, '视频文件不能为空'],
        validate: {
            validator: function(v) {
                // 支持相对路径和完整URL
                return /^(\/uploads\/videos\/.+\.(mp4|mov|avi|wmv|flv|mkv)$|(http|https):\/\/.+\.(mp4|mov|avi|wmv|flv|mkv)$)/i.test(v);
            },
            message: props => `${props.value} 不是有效的视频文件URL!`
        }
    },
    
    // 视频状态
    status: {
        type: String,
        required: true,
        enum: {
            values: ['draft', 'published', 'archived'],
            message: '状态必须是draft(草稿)、published(已发布)或archived(已归档)'
        },
        default: 'draft'
    },
    
    // 视频价格（单位：分）
    price: {
        type: Number,
        required: true,
        min: [0, '价格不能为负数'],
        default: 0
    },
    
    // 上传人（关联用户表）
    uploader: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, '上传人不能为空']
    },
    
    // 上传人用户名（冗余存储，便于查询）
    uploaderUsername: {
        type: String,
        required: [true, '上传人用户名不能为空']
    },
    
    // 上传时间
    uploadTime: {
        type: Date,
        default: Date.now
    },
    
    // 更新时间
    updateTime: {
        type: Date,
        default: Date.now
    },
    
    // 视频描述
    description: {
        type: String,
        maxlength: [500, '描述不能超过500个字符']
    },
    
    // 视频时长（秒）
    duration: {
        type: Number,
        min: [0, '时长不能为负数']
    },
    
    // 视频大小（字节）
    fileSize: {
        type: Number,
        min: [0, '文件大小不能为负数']
    }
}, {
    timestamps: { 
        createdAt: 'uploadTime', 
        updatedAt: 'updateTime' 
    }
});

const VideoResource = mongoose.model('VideoResource', videoResourceSchema);

// 课程表
const courseSchema = new mongoose.Schema({
    // 课程名称
    name: {
        type: String,
        required: true,
        trim: true,
        maxlength: 100
    },
    // 课程描述
    description: {
        type: String,
        maxlength: 500
    },
    // 课程价格（单位：分）
    price: {
        type: Number,
        required: true,
        min: 0,
        default: 0
    },
    // 课程封面图片URLs（支持多个封面图片）
    coverImageUrls: [{
        type: String,
        required: false, // 改为非必需
        validate: {
            validator: function(v) {
                // 如果为空或null，则跳过验证
                if (!v) return true;
                // 支持相对路径和完整URL
                return /^(\/uploads\/course-images\/.+\.(jpg|jpeg|png|gif|webp)$|(http|https):\/\/.+\.(jpg|jpeg|png|gif|webp)$)/i.test(v);
            },
            message: props => `${props.value} 不是有效的图片URL!`
        }
    }],
    // 课程视频资源（存储VideoResource的ObjectId）
    videoResources: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'VideoResource',
        required: false // 允许空数组
    }],
    // 课程图片资源
    imageResources: [{
        type: String, // 存储图片URL
        required: false // 允许空数组
    }],
    // 课程文档资源
    fileResources: [{
        type: String, // 存储文档文件URL
        required: false // 允许空数组
    }],
    // 课程讲师
    teacher: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Teacher',
        required: true
    },
    // 课程讲师名称
    teacherName: {
        type: String,
        required: true
    },
    // 课程上传人
    uploader: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    // 课程上传人用户名
    uploaderUsername: {
        type: String,
        required: true
    },
    // 课程添加时间
    createdAt: {
        type: Date,
        default: Date.now
    },
    // 课程更新时间
    updatedAt: {
        type: Date,
        default: Date.now
    }
});

const Course = mongoose.model('Course', courseSchema);

// 订单表
const orderSchema = new mongoose.Schema({
    // 订单编号
    orderId: {
        type: String,
        required: true,
        unique: true,
        validate: {
            validator: function(v) {
                return /^\d{7}$/.test(v); // 7位数字
            },
            message: props => `${props.value} 不是有效的订单编号! 订单编号必须是7位数字`
        }
    },
    // 用户昵称
    userNickname: {
        type: String,
        required: true,
        trim: true,
        maxlength: 50
    },
    // 用户手机号
    phone: {
        type: String,
        required: true,
        validate: {
            validator: function(v) {
                return /^1[3-9]\d{9}$/.test(v);
            },
            message: props => `${props.value} 不是有效的手机号码!`
        }
    },
    // 商品类型 (course 或 book)
    productType: {
        type: String,
        required: true,
        enum: ['course', 'book'],
        default: 'book'
    },
    // 商品名称
    productName: {
        type: String,
        required: true,
        trim: true,
        maxlength: 100
    },
    // 商品ID
    productId: {
        type: String,
        required: true
    },
    // 订单金额（单位：元）
    orderAmount: {
        type: Number,
        required: true,
        min: 0,
        set: v => parseFloat(v.toFixed(2)) // 保留2位小数
    },
    // 订单状态
    orderStatus: {
        type: String,
        required: true,
        enum: ['pending', '已支付', 'closed', 'refunded', 'cancelled'],
        default: 'pending'
    },
    // 支付宝交易号
    alipayTradeNo: {
        type: String,
        default: null
    },
    // 提交时间
    submitTime: {
        type: Date,
        default: Date.now
    },
    // 支付时间
    payTime: {
        type: Date
    },
    // 关闭时间
    closeTime: {
        type: Date
    },
    // 退款时间
    refundTime: {
        type: Date
    },
    // 订单备注
    remark: {
        type: String,
        maxlength: 200
    }
}, {
    timestamps: { 
        createdAt: 'submitTime', 
        updatedAt: 'updateTime' 
    }
});

const Order = mongoose.model('Order', orderSchema);

// 课程排班表
const scheduleSchema = new mongoose.Schema({
  // 课程ID
  courseId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Course',
    required: [true, '课程ID不能为空']
  },
  
  // 教师ID
  teacherId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Teacher',
    required: [true, '教师ID不能为空']
  },
  
  // 课程名称（冗余存储）
  courseName: {
    type: String,
    required: [true, '课程名称不能为空']
  },
  
  // 教师姓名（冗余存储）
  teacherName: {
    type: String,
    required: [true, '教师姓名不能为空']
  },
  
  // 排班日期
  date: {
    type: Date,
    required: [true, '排班日期不能为空']
  },
  
  // 开始时间
  startTime: {
    type: String,
    required: [true, '开始时间不能为空'],
    validate: {
      validator: function(v) {
        return /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(v);
      },
      message: props => `${props.value} 不是有效的时间格式!`
    }
  },
  
  // 结束时间
  endTime: {
    type: String,
    required: [true, '结束时间不能为空'],
    validate: {
      validator: function(v) {
        return /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(v);
      },
      message: props => `${props.value} 不是有效的时间格式!`
    }
  },
  
  // 教室
  classroom: {
    type: String,
    required: [true, '教室不能为空'],
    trim: true,
    maxlength: [50, '教室名称不能超过50个字符']
  },
  
  // 状态
  status: {
    type: String,
    required: true,
    enum: {
      values: ['scheduled', 'ongoing', 'completed', 'cancelled'],
      message: '状态必须是scheduled(已安排)、ongoing(进行中)、completed(已完成)或cancelled(已取消)'
    },
    default: 'scheduled'
  },
  
  // 备注
  description: {
    type: String,
    maxlength: [500, '备注不能超过500个字符']
  },
  
  // 创建人
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: [true, '创建人不能为空']
  },
  
  // 创建人用户名
  createdByUsername: {
    type: String,
    required: [true, '创建人用户名不能为空']
  }
}, {
  timestamps: { 
    createdAt: 'createdAt', 
    updatedAt: 'updatedAt' 
  }
});

// 添加索引以提高查询性能
scheduleSchema.index({ courseId: 1, date: 1 });
scheduleSchema.index({ teacherId: 1, date: 1 });
scheduleSchema.index({ status: 1 });

const Schedule = mongoose.model('Schedule', scheduleSchema);

module.exports = {
    User,
    Student,
    Teacher,
    VideoResource,
    Course,
    Order,
    lxtuserModel,
    Schedule
};
